<template>
  <div class="app-container activity">
    <el-card class="box-card" shadow="false">
      <div slot="header" class="clearfix">
        <router-link :to="{name: 'activity-view-list'}">
          <el-button plain icon="el-icon-back" size="small" :round="true">
            返回
          </el-button>
        </router-link>
      </div>
      <el-row>
        <el-col :span="24">
          <div class="steps">
            <el-steps :active="activeForm" align-center>
              <el-step title="选择模板"></el-step>
              <el-step title="设置内容样式"></el-step>
              <el-step title="设置触发条件"></el-step>
            </el-steps>
          </div>

          <el-tabs v-model="activeName" v-if="activeForm===1">
            <el-tab-pane label="弹窗" name="dialog">
              <div class="marketing-tabs">
                <div class="marketing-tabs-tabpane">
                  <div alt="已选中" class="popupTemplate" v-for="(item, index) in dialogTemplates" :key="index"
                       :class="{'popupTemplate__selected': currentKey === item.key}" @click="handleSelectChoose(item.key)">
                    <div class="template__image" :class="item.bg"></div>
                    <div class="step1__name">{{ item.title }}</div>
                    <div class="step1__operation">
                      <div class="popupTemplate__preview" @click="handlePreviewModule(item.bg)">预览</div>
                      <div class="popupTemplate__select" @click="handleSelectModule(item.key)">选择</div>
                    </div>
                  </div>
                </div>
              </div>
            </el-tab-pane>
            <!-- 弹窗模块预览弹窗 -->
            <div @click="dialogTableVisible=false">
              <el-dialog :visible.sync="dialogTableVisible" customClass="customWidth" :close-on-click-modal="false">
                <div class="template__image select__img" :class="selectItemBg"></div>
              </el-dialog>
            </div>

            <el-tab-pane label="公告栏" name="notice">
              <div class="placard-tabs">
                <div class="placard-tabs-tabpane" v-for="(item, index) in noticeTemplates" :key="index">
                  <div class="placard-tabs-image" :class="item.bg"></div>
                  <div class="placard-tabs-title">{{ item.title }}</div>
                  <div class="placard-tabs__select">
                    <div class="placard-tabs-button" @click="handleSelectModule(item.key)">选择</div>
                  </div>
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>

          <subscription-editor :module-name="currentModal" v-if="activeForm===2"
                               @on-save="handleStep2" :reset-style="resetStyle"></subscription-editor>

          <el-form ref="siteForm" :model="conditions" :rules="rules" label-width="120px" v-if="activeForm===3">
            <h4>触发条件</h4>
            <el-form-item label="展示页面" prop="showPage">
              <el-radio-group v-model="conditions.showPage" class="radio-item-group">
                <el-radio label="all">全部页面（不包含结账支付页、登陆注册页）</el-radio>
                <el-radio label="part" class="radio-item">
                  指定页面
                </el-radio>
                <el-checkbox-group v-model="conditions.partCheckList" v-if="conditions.showPage === 'part'">
                  <el-checkbox v-for="(item, index) in pagesPath" :label="item.name" :key="index" @change="handleWhichChecked">{{item.title}}</el-checkbox>
                </el-checkbox-group>
                <el-input
                    type="text"
                    placeholder="请输入指定url"
                    v-model="pagesPath[7].title"
                    maxlength="50"
                    show-word-limit
                    style="width: 400px;margin-top:10px;"
                    v-if="showInputChecked"
                />
              </el-radio-group>
            </el-form-item>
            <el-form-item label="展示频次" prop="frequency">
              <el-radio-group v-model="conditions.frequency">
                <el-radio label="EveryTime">每次</el-radio>
                <el-radio label="OneTime">仅一次</el-radio>
              </el-radio-group>
            </el-form-item>
            <h4>生效时间</h4>
            <el-form-item label="活动时间" prop="startDate" class="hasWidth">
              <el-date-picker
                  v-model="conditions.startDate"
                  type="datetime"
                  placeholder="开始日期"
                  align="right" value-format="yyyy-MM-dd HH:mm:ss" :disabled="bindActivity">
              </el-date-picker>
              <span>--</span>
              <el-date-picker
                  v-model="conditions.endDate"
                  type="datetime"
                  placeholder="结束日期"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  align="right" :disabled="endDateCheck || bindActivity">
              </el-date-picker>
              <el-checkbox v-model="endDateCheck" :disabled="bindActivity">不限时间</el-checkbox>
            </el-form-item>
            <h4>活动名称</h4>
            <el-form-item prop="name">
              <el-input
                  type="text"
                  placeholder="请输入活动名称"
                  v-model="conditions.name"
                  maxlength="50"
                  show-word-limit
                  style="width: 400px"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="activeForm = 2">上一步</el-button>
              <el-button type="primary" @click="handleSubmit('siteForm')" :loading="submitLoading">保存</el-button>
              <el-button @click="handleReset('siteForm')">取消</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script>
import uploadFile from '@/components/Upload/uploadFile';
import subscriptionEditor from '@/components/theme-editor/subscriptionEditor';
import {currency, utcFormat} from '@/utils/filters';
import {
    addActivityView
} from '@/api/marketing';
import {mapGetters} from 'vuex';

export default {
    name: 'activity-view-add',
    components: {
        subscriptionEditor
    },
    data () {
        return {
            activeForm: 1,
            couponCodeId: 0,
            priceReduceId: 0,
            viewSettings: '',
            bindActivity: false,
            endDateCheck: false,
            activeName: 'dialog',
            currentKey: 'ReductionActivity',
            currentModal: 'BulletinBoardCountDown',
            dialogTemplates: [
                {
                    title: '满减活动',
                    key: 'ReductionActivity',
                    bg: 'template_rebate'
                },
                {
                    title: '营销活动',
                    key: 'MarketingActivities',
                    bg: 'template_marketing'
                },
                {
                    title: '订阅弹窗',
                    key: 'Subscription',
                    bg: 'template_subscription'
                },
                {
                    title: '限时活动',
                    key: 'FlashSale',
                    bg: 'template_flash_sale'
                }
            ],
            noticeTemplates: [
                {
                    title: '活动倒计时',
                    key: 'BulletinBoardCountDown',
                    bg: 'template_bulletin_board_countDown'
                },
                {
                    title: '满减提醒',
                    key: 'BulletinBoardReduction',
                    bg: 'template_board_reduction'
                }
            ],
            conditions: {
                name: '',
                endDate: '',
                startDate: '',
                showPage: 'all',
                partCheckList: [],
                frequency: 'OneTime'
            },
            pagesPath: [{
                title: '首页',
                name: 'index'
            }, {
                title: '专辑详情页',
                name: 'collection-id'
            }, {
                title: '商品详情页',
                name: 'products-id'
            }, {
                title: '购物车',
                name: 'bag'
            }, {
                title: '活动页',
                name: 'rebate-id'
            }],
            currencyList: [
                {value: 'USD', name: 'USD'}
            ],
            timeZoneList: [
                {value: 'UTC-5', name: '(UTC-05:00) 美国东部时间'}
            ],
            uploadPath: process.env.VUE_APP_BASE_API + '/upload-file',
            rules: {
                name: [
                    {required: true, message: '请输入活动名称', trigger: 'blur'}
                ],
                showPage: [
                    {required: true, message: '请选择展示页面', trigger: 'blur'}
                ],
                frequency: [
                    {required: true, message: '请选择展示频率', trigger: 'blur'}
                ],
                startDate: [
                    {required: true, message: '请设置活动时间', trigger: 'blur'}
                ],
                timeZone: [
                    {required: true, message: '请选择店铺时区', trigger: 'blur'}
                ],
                siteEmail: [
                    {required: true, message: '请输入站点邮箱', trigger: 'blur'},
                    {type: 'email', message: '邮箱格式不正确', trigger: 'blur'}
                ],
                financeEmail: [
                    {type: 'email', message: '邮箱格式不正确', trigger: 'blur'}
                ],
                serviceEmail: [
                    {required: true, message: '请输入客服邮箱', trigger: 'blur'},
                    {type: 'email', message: '邮箱格式不正确', trigger: 'blur'}
                ]
            },
            submitLoading: false,
            dialogTableVisible: false,
            selectItemBg: 'template_rebate',
            resetStyle: true
        };
    },
    computed: {
        ...mapGetters(['timeZone']),
        siteId () {
            return this.$store.state.user.siteId;
        }
    },
    mounted () {
    },
    methods: {
        handleSubmit (name) {
            this.$refs[name].validate(valid => {
                if (valid) {
                    this.submitLoading = true;
                    this.handleSaveView();
                } else {
                    this.submitLoading = false;
                }
            });
        },
        handleSelectChoose (name) {
            this.currentKey = name;
        },
        handlePreviewModule (value) {
            this.dialogTableVisible = true;
            this.selectItemBg = value;
        },
        handleReset (name) {
            this.$router.push({name: 'activity-view-list'});
        },
        handleSelectModule (name) {
            this.currentKey = name;
            this.currentModal = name;
            this.activeForm = 2;
        },
        handleStep2 (value) {
            this.couponCodeId = 0;
            this.priceReduceId = 0;
            this.bindActivity = false;
            this.endDateCheck = false;
            this.conditions.endDate = null;
            this.conditions.startDate = null;
            let priceReduceId = value.priceReduceId;
            let couponCodeId = value.couponCodeId;
            if (priceReduceId && priceReduceId > 0) {
                this.bindActivity = true;
                this.priceReduceId = priceReduceId;
                if (value.startTime) {
                    this.conditions.startDate = utcFormat(value.startTime, 'YYYY-MM-DD HH:mm:ss', this.timeZone);
                }
                if (value.endTime) {
                    this.conditions.endDate = utcFormat(value.endTime, 'YYYY-MM-DD HH:mm:ss', this.timeZone);
                } else {
                    this.endDateCheck = true;
                }
            }
            if (couponCodeId && couponCodeId > 0) {
                this.bindActivity = true;
                this.couponCodeId = value.couponCodeId;
                if (value.startTime) {
                    this.conditions.startDate = utcFormat(value.startTime, 'YYYY-MM-DD HH:mm:ss', this.timeZone);
                }
                if (value.endTime) {
                    this.conditions.endDate = utcFormat(value.endTime, 'YYYY-MM-DD HH:mm:ss', this.timeZone);
                } else {
                    this.endDateCheck = true;
                }
            }
            this.viewSettings = JSON.stringify(value);
            this.activeForm = 3;
            this.handleWhichChecked();
        },
        handleSaveView () {
            if (this.conditions.showPage === 'part' && this.conditions.partCheckList.length <= 0) {
                this.$message.error('请先设置自定义展示页面');
                this.submitLoading = false;
                return false;
            }
            let tempStartTime = this.conditions.startDate;
            if (tempStartTime == null || tempStartTime === '') {
                this.$message.error('请先设置活动开始时间');
                this.submitLoading = false;
                return false;
            }
            let tempEndTime = this.conditions.endDate;
            if (!this.endDateCheck && (!tempEndTime || tempEndTime === '')) {
                this.$message.error('请先设置活动结束时间');
                this.submitLoading = false;
                return false;
            }
            let activityView = {
                siteId: this.siteId,
                name: this.conditions.name,
                showType: this.activeName,
                activityTemplate: this.activeName === 'dialog' ? this.currentKey : this.currentModal,
                pageType: this.conditions.showPage,
                showFrequency: this.conditions.frequency,
                startTime: new Date(tempStartTime + ' UTC' + this.timeZone).getTime(),
                settings: this.viewSettings
            };
            if (this.conditions.showPage === 'all') {
                activityView.showPages = '';
            } else {
                activityView.showPages = this.conditions.partCheckList.join(',');
            }
            if (tempEndTime != null && tempEndTime !== '') {
                activityView.unlimited = 0;
                activityView.finishTime = new Date(tempEndTime + ' UTC' + this.timeZone).getTime();
            }
            if (this.endDateCheck) {
                activityView.unlimited = 1;
                activityView.finishTime = null;
            }
            if (this.priceReduceId && this.priceReduceId > 0) {
                activityView.priceReduceId = this.priceReduceId;
            }
            if (this.couponCodeId && this.couponCodeId > 0) {
                activityView.couponCodeId = this.couponCodeId;
            }
            addActivityView(activityView).then(res => {
                this.$message({ type: 'success', message: '新增成功!' });
                this.$router.push({name: 'activity-view-list'});
                this.submitLoading = false;
            });
        },
        handleWhichChecked () {
            if (this.conditions.partCheckList.indexOf('url') !== -1) {
                this.showInputChecked = true;
            } else {
                this.showInputChecked = false;
            }
        },
        timestampToTime (timestamp) {
            var date = new Date(timestamp);// 时间戳为10位需*1000，时间戳为13位的话不需乘1000
            var Y = date.getFullYear() + '-';
            var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
            var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
            var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
            var m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
            var s = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
            let strDate = Y + M + D + h + m + s;
            return strDate;
        }
    }
};

</script>

<style scoped lang="scss">
.steps {
  width: 80%;
  margin: 10px auto;
}

.marketing-tabs {
  display: flex;
  flex-direction: row;
  transition: margin-left 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
  will-change: margin-left;
  width: 100%;

  .marketing-tabs-tabpane {
    display: flex;
    flex-shrink: 0;
    width: 100%;
    -webkit-backface-visibility: hidden;
    opacity: 1;
    transition: opacity 0.45s;
    flex-wrap: wrap;

    .popupTemplate {
      position: relative;
      width: 260px;
      border: 1px solid #e0e2e7;
      margin: 0 20px 20px 0;

      &__selected {
        position: relative;

        &:before {
          content: '';
          position: absolute;
          width: 0;
          height: 0;
          top: 0;
          left: 0;
          border: 1px solid;
          border-bottom: 31px solid transparent;
          border-left: 31px solid;
          border-right: 31px solid transparent;
          border-top: 31px solid;
          color: #1f7df8;
        }

        &:after {
          content: attr(alt);
          position: absolute;
          font-size: 12px;
          font-weight: 600;
          top: 12px;
          left: 2px;
          color: #fff;
          transform: rotate(-45deg);
        }
      }

      .step1__name {
        height: 50px;
        text-align: center;
        display: block;
        line-height: 50px;
      }

      .step1__operation {
        display: none;
        align-items: center;
        justify-content: space-around;
        height: 50px;
        background-color: #f7f7f7;
        border-top: 1px solid #eef0f5;

        .popupTemplate__preview, .popupTemplate__select {
          height: 50px;
          display: flex;
          flex: 1 1 auto;
          justify-content: center;
          align-items: center;
          font-size: 14px;
          color: #7e849c;
          &:hover {
            background-color: #1F7DF8;
            color: #fff;
          }
        }
      }

      &:hover {
        .step1__name {
          display: none;
        }

        .step1__operation {
          display: flex;
        }
      }
    }
  }
}
.placard-tabs {
  width: 100%;
  .placard-tabs-tabpane {
    width: 100%;
    position: relative;
    border: 1px solid #eef0f5;
    &:hover .placard-tabs__select {
      display: flex;
    }
    .placard-tabs-image {
      width: 100%;
      height: 100px;
      background-repeat: no-repeat;
      background-position: center;
      background-size: 100%;

      &.template_board_reduction {
        background-image: url("../../assets/images/BulletinBoardReduction.png");
      }

      &.template_bulletin_board_countDown {
        background-image: url("../../assets/images/BulletinBoardCountDown.png");
      }

      &.template_rebate {
        background-image: url("../../assets/images/subscription1.png");
      }

      &.template_flash_sale {
        background-image: url("../../assets/images/flashSale.png");
      }

      &.template_marketing {
        background-image: url("../../assets/images/marketingActivities.png");
      }
    }
    .placard-tabs-title {
      width: 100%;
      height: 50px;
      line-height: 50px;
      background-color: #f7f7f7;
      text-align: center;
      font-size: 16px;
      font-weight: 555;
      color: rgba(0, 0, 0, 0.65);
    }
    .placard-tabs__select {
      display: none;
      position: absolute;
      top: 0;
      left: 0;
      z-index: 9;
      width: 100%;
      height: 100px;
      background: rgba(0,0,0,0.3);
      .placard-tabs-button {
        width: 90px;
        height: 40px;
        line-height: 40px;
        display: inline-block;
        margin: 30px auto;
        text-align: center;
        color: #fff;
        background-color: #3364F5;
        border-radius: 4px;
        font-size: 15px;
        &:hover {
          background-color: #409EFF;
        }
      }
    }
  }
}
.template__image {
  width: 100%;
  height: 220px;
  background-repeat: no-repeat;
  background-position: center;
  background-size: 100%;

  &.template_board_reduction {
    background-image: url("../../assets/images/BulletinBoardReduction.png");
  }

  &.template_bulletin_board_countDown {
    background-image: url("../../assets/images/BulletinBoardCountDown.png");
  }

  &.template_rebate {
    background-image: url("../../assets/images/subscription1.png");
  }

  &.template_flash_sale {
    background-image: url("../../assets/images/flashSale.png");
  }

  &.template_marketing {
    background-image: url("../../assets/images/marketingActivities.png");
  }
  &.template_subscription {
    background-image: url("../../assets/images/subscription.png");
  }
}
.select__img {
  width: 500px;
  height: 800px;
}
</style>

<style scoped lang="scss">
@import '../../components/theme-editor/_common/css/variable';

$siteTopHeight: 80px;
$toolBarWidth: 260px;
$dragAreaWidth: 1920px;

/*预览模式 同步样式重置*/
.previewBox {
  .toolsBar, .leftCaret {
    display: none;
  }

  .container {
    height: 100vh;
    padding-left: 0;
  }

  .contentWrap, .dragAreaWrap {
    overflow-x: hidden;
  }

  .contentBox, .dragAreaWrap {
    width: auto;
  }

  :global {
    .vueEditor_viewComponentBox {
      margin-left: 50%;
      transform: translate(-50%, 0);
      cursor: auto;
      box-shadow: none;

      &:after {
        display: none;
        content: none;
      }
    }
  }
}

.container {
  position: relative;
  box-sizing: border-box;
  padding-left: 0;
  padding-top: 10px;
  height: calc(100vh - 80px);
  transition: 0.2s ease;
}

.hasTools {
  padding-left: $toolBarWidth;

  :global .el-icon-caret-right {
    transform: rotate(180deg);
  }
}

/*tools*/
.leftCaret {
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  position: absolute;
  width: 18px;
  height: 50px;
  background: $colorWhite;
  top: 50%;
  margin-top: -25px;
  box-shadow: 0 0 4px 0 color($colorBlack 0.1);
  transition: all ease 0.3s;
  border-radius: 0 10px 10px 0;
  z-index: 9;

  &:hover {
    box-shadow: 0 0 4px 0 color($colorBlack 0.2);
    opacity: 1;
  }
}

.toolsBar {
  position: absolute;
  left: 0;
  top: 10px;
  bottom: 0;
  background: $colorWhite;
  width: $toolBarWidth;
  overflow: auto;
  box-shadow: 0 0 4px 0 color($colorBlack 0.2);
  z-index: 2;

  &::-webkit-scrollbar {
    width: 0;
    height: 0;
  }
}

/*content area*/
.contentWrap {
  position: relative;
  overflow: auto;
  height: 100%;

  &::-webkit-scrollbar {
    width: 6px;
    height: 10px;
  }

  &::-webkit-scrollbar-track {
    background-color: $backgroundColorBase;
  }

  &::-webkit-scrollbar-thumb {
    border-radius: 10px;
    background-color: $colorTextPlaceholder;
  }
}

.contentBox {
  position: relative;
  min-height: 100%;
}

.dragAreaWrap {
  transform-origin: top center;
  position: relative;
  margin: 0 auto;
}

.tipBox {
  pointer-events: none;
  top: 20px;
  position: absolute;
  left: 0;
  width: 100%;
  text-align: center;
  margin: 30vh 0;

  p {
    margin: 20px 0;
    font-size: 16px;
  }
}

.dragArea {
  /* min-height: calc(100vh - var(--site-top-height) - 50px); */
  min-height: calc(100vh + 100px);
  background-color: #f5f5f5;
  padding: 10px 0;

  :global {
    .draggableToolItem {
      width: 100%;
      max-width: 100%;

      &:local {
        &.ghost {
          background-color: color($colorPrimary 0.4) !important;
          box-shadow: 0 3px 14px 3px color($colorPrimary 0.6), 0 10px 10px 1px color($colorPrimary 0.6);
          height: 120px !important;
          padding: 20px;

          & > div {
            width: 100%;
            height: 100%;
            background-color: $colorWhite;
          }

          p {
            font-size: 16px;
            line-height: 24px;
          }
        }
      }
    }

    .emptyBox {
      min-height: 350px;
      display: flex;
      justify-content: center;
      align-items: center;
    }

    .viewEmpty_IconBox {
      color: color($checkboxColor 0.7);
      font-size: 50px;
      text-align: center;
    }

    .el-image {
      vertical-align: top;
    }
  }
}

.ghost {
  opacity: 0.5;
}
.Template6__layer {
  position: absolute!important;
  width: 60% !important;
  height: 90% !important;
}

.draggableItem {
  width: 100%;
}
.Template8__layer {
  background-color: transparent!important;
  padding: 15vh 0;
}
//满减提醒
.Banner6__layer {
  position: relative!important;
}
// 活动倒计时
.Banner3__layer {
  position: relative!important;
}
</style>
<style lang="scss">
.activity{
  .radio-item-group {
    display: flex;
    justify-content: center;
    flex-direction: column;
    align-items: flex-start;
    .el-radio{
      margin-bottom: 10px;
    }

    .radio-item {
      display: flex;
      align-items: center;

      .el-radio__label {
        display: flex;
        align-items: center;
        .el-checkbox-group{
          margin-left: 20px;
        }
      }
    }
  }
}
.customWidth {
  box-sizing: border-box!important;
  width:100%;
  height: 100%;
  margin: 0!important;
  background-color: transparent;
  .el-dialog__header  {
    padding: 0;
    .el-dialog__headerbtn{
      color: #fff;
      font-size: 24px;
      font-weight: bold;
      z-index: 99;
      .el-dialog__close{
        color: inherit;
      }
    }
  }
  .el-dialog__body  {
    padding: 0;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    height: 100%;
    .Banner3__layer{
      height: auto;
    }
  }
}
//限时活动
.Template8PcWrap {
  position: relative!important;
}
</style>
